//import ca.newcommerce.youtube.data.VideoData;

import components.curr_playlist;
import components.popUpWin_onlineAlternative;

import events.PlaySongEvent;
import events.PlayVideoEvent;

import flash.media.Video;

import mx.charts.AreaChart;
import mx.collections.ArrayCollection;
import mx.controls.*;
import mx.events.CloseEvent;
import mx.events.DragEvent;
import mx.events.FlexMouseEvent;
import mx.events.ListEvent;
import mx.events.MenuEvent;
import mx.managers.PopUpManager;

private var alert:Alert;
private var currentElementIndex:int = -1;

// -------------------------- right click on a row stuff ----------------------------------
[Bindable]
private var cm:ContextMenu;
private var ShuffleState:Boolean=false;

public function init():void {
	
	/*test();*/

	var addToPlaylistCmi:ContextMenuItem = new ContextMenuItem("Add to playlist", true);
	addToPlaylistCmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, contextMenuItem_addToPlaylist);
	
	var viewInfoCmi:ContextMenuItem = new ContextMenuItem("Get info", true);
	viewInfoCmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, contextMenuItem_showInfo);
	
	var deleteCmi:ContextMenuItem = new ContextMenuItem("Delete song", true);
	deleteCmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, contextMenuItem_deleteSelect);
	
	var shareCmi:ContextMenuItem = new ContextMenuItem("Suggest song to freinds", true);
	shareCmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, contextMenuItem_shareSong);
	
	var videoCmi:ContextMenuItem = new ContextMenuItem("Change video", true);
	videoCmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, contextMenuItem_changeVideo);
	
	cm = new ContextMenu();
	cm.hideBuiltInItems();
	cm.customItems = [addToPlaylistCmi, viewInfoCmi, deleteCmi, shareCmi, videoCmi];
	cm.addEventListener(ContextMenuEvent.MENU_SELECT, contextMenu_menuSelect);
}

private function contextMenu_menuSelect(evt:ContextMenuEvent):void {
	songsDataGrid.selectedIndex = lastRollOverIndex;
}


// -------- edit info option ---------

private var popup_info:popUpWin_getInfo;

public function contextMenuItem_showInfo(evt:ContextMenuEvent):void
{
	if (songsDataGrid.selectedIndex != -1)
	{
		var songObj:Object = songsDataGrid.selectedItem;
		this.parentApplication.getMoreSongInfo(songObj.id);
	}
}

public function openEditInfoPopUp(infoObj:Object):void
{
	if (songsDataGrid.selectedIndex != -1)
	{
		var songObj:Object = songsDataGrid.selectedItem;
		
		popup_info = PopUpManager.createPopUp(this.parent.parent,popUpWin_getInfo,true) as popUpWin_getInfo;
		PopUpManager.centerPopUp(popup_info);
		popup_info.addEventListener(Event.CLOSE, closePopUpWindow_info);
		popup_info.addEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, closePopUpWindow_info);
		popup_info.setSongObj(songObj, songsDataGrid.selectedIndex);
		popup_info.setInfoFromServer(infoObj);
	}
}

private function closePopUpWindow_info(evt:Event):void {
	PopUpManager.removePopUp(popup_info);
}

public function changeSongObj(index:Number, songObj:Object):void
{
	this.gridData.removeItemAt(index);
	this.gridData.addItemAt(songObj, index);
}

// ------ add to playlist option ------

private var popup_add:popUpWin_addToPlaylist;

public function contextMenuItem_addToPlaylist(evt:ContextMenuEvent):void
{
	if (songsDataGrid.selectedIndex != -1)
	{
		var songObj:Object = songsDataGrid.selectedItem;
		
		popup_add = PopUpManager.createPopUp(this.parent.parent,popUpWin_addToPlaylist,true) as popUpWin_addToPlaylist;
		PopUpManager.centerPopUp(popup_add);
		popup_add.addEventListener(Event.CLOSE, closePopUpWindow_add);
		popup_add.addEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, closePopUpWindow_add);
		popup_add.getPlaylistList(this.parentApplication.getPlaylistList());
		popup_add.setSongObj(songObj);
	}
}

private function handlePlayVideoEvent(playVideoEvent:PlayVideoEvent):void{
	dispatchEvent(playVideoEvent);
}

private function closePopUpWindow_add(evt:Event):void {
	PopUpManager.removePopUp(popup_add);
}

// ----------- share song option ----------

private var popup_share:popUpWin_shareSong;

public function contextMenuItem_shareSong(evt:ContextMenuEvent):void
{
	if (songsDataGrid.selectedIndex != -1)
	{
		var songObj:Object = songsDataGrid.selectedItem;
		
		popup_share = PopUpManager.createPopUp(this.parent.parent,popUpWin_shareSong,true) as popUpWin_shareSong;
		PopUpManager.centerPopUp(popup_share);
		popup_share.addEventListener(Event.CLOSE, closePopUpWindow_share);
		popup_share.addEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, closePopUpWindow_share);
		popup_share.setSongObj(songObj);
	}
}

private function closePopUpWindow_share(evt:Event):void {
	PopUpManager.removePopUp(popup_share);
}

// -------- change video option ------

private var popup_videoAlternative:popUpWin_onlineAlternative;
public function contextMenuItem_changeVideo(evt:ContextMenuEvent):void
{
	if (songsDataGrid.selectedIndex != -1)
	{
		var songObj:Object = songsDataGrid.selectedItem;
		
		popup_videoAlternative = PopUpManager.createPopUp(this.parent.parent,popUpWin_onlineAlternative,true) as popUpWin_onlineAlternative;
		PopUpManager.centerPopUp(popup_videoAlternative);
		popup_videoAlternative.addEventListener(Event.CLOSE, closePopUpWindow_videoAlternative);
		popup_videoAlternative.addEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, closePopUpWindow_videoAlternative);
		popup_videoAlternative.addEventListener(PlayVideoEvent.PLAY_VIDEO_EVENT,handlePlayVideoEvent);
		popup_videoAlternative.setSongObj(songObj, songsDataGrid.selectedIndex);
	}
}

private function closePopUpWindow_videoAlternative(evt:Event):void {
	PopUpManager.removePopUp(popup_videoAlternative);
}

// -------- delete song option --------

public function contextMenuItem_deleteSelect(evt:ContextMenuEvent):void
{
	if (songsDataGrid.selectedIndex != -1)
	{
		var songObj:Object = songsDataGrid.selectedItem;
		var alertText:String;
		
		if (this.parentApplication.isDefaultPlaylist(plKey))
		{
			alertText = "Are you sure you want to delete " + songObj.name + " from all the playlists?";
			Alert.show(alertText, "Delete playlist?", Alert.YES | Alert.NO, this, deleteSongNow);
		} else {
			alertText = "Are you sure you want to delete " + songObj.name + " from this playlists?";
			Alert.show(alertText, "Delete playlist?", Alert.YES | Alert.NO, this, deleteSongNow);
		}
	}
}

private function deleteSongNow(event:CloseEvent):void
{
	if (event.detail==Alert.YES)
	{
		var songObj:Object = songsDataGrid.selectedItem;
		this.parentApplication.deleteSongFromPlaylist(this.plKey, songObj.keyString, songsDataGrid.selectedIndex);
	}
}



// -------------------------- Showing Songs on the playlist -------------------------------
/*private var testArr:Array = 
	[{title:"title1", duration:"duration1", id:"id1", name:"name1", time:"time1",artist:"artist1", album:"album1", genre:"genre1",keyString:"keyString1", isLocal:false},
{title:"title2", duration:"duration2", id:"id2", name:"name2", time:"time2",artist:"artist2", album:"album2", genre:"genre2",keyString:"keyString2", isLocal:true}];

private function test():void
{
	gridData = new ArrayCollection(testArr);
}*/

[Bindable] 
public var gridData:ArrayCollection =  new ArrayCollection();

private var plKey:String = null;


public function getCurrentPlaylist():String
{
	return this.plKey;
}

public function addSongToThisPlaylist(song:Object):Number
{
	//song.rowNum = this.gridData.length + 1;
	this.gridData.addItem(song);
	return gridData.getItemIndex(song);
}

public function deleteSongFromThisPlaylist(deletedSongIndex:Number):void
{
	/*var rowNum:int = this.gridData.getItemAt(deletedSongIndex).rowNum;
	this.changeRowNumAfterDelete(rowNum);*/
	
	this.gridData.removeItemAt(deletedSongIndex);
}

public function loadPlaylist(plKey:String, songsArr:ArrayCollection):void
{
	// saving the current playlist key for future actions like delete song...
	this.plKey = plKey;
	
	/*for (var i:int = 0; i < songsArr.length; i++)
	{
		this.addRowNumber(songsArr[i], i);
	}*/
	
	// showing the songs in the data grid. 
	gridData = songsArr;
	currentElementIndex = -1;
	
}

/*private function addRowNumber(songObj:Object, rowIndex:int):void
{
	songObj.rowNum = rowIndex + 1;
}

private function changeRowNumAfterDelete(deletedRow:int):void
{
	for (var i:int = 0; i < this.gridData.length; i++)
	{
		if (this.gridData[i].rowNum > deletedRow)
		{
			this.gridData[i].rowNum -= 1;
		}
	}
}*/

// -------------------------- Handling play video events. ---------------------------------

protected function songsDataGrid_itemDoubleClickHandler(event:ListEvent):void
{
	currentElementIndex = event.rowIndex;
	var newVideo:Object = gridData.getItemAt(currentElementIndex);
	var playSongEvent:PlaySongEvent = new PlaySongEvent(newVideo,this,true);
	dispatchEvent(playSongEvent);
}

public function nextVideo():void{
	if(ShuffleState==true){
		var length:int=(gridData.length-1);
		playRequestedVideoIndexIfExists(generateRandomNumber(length));
	}else{
		var requestedIndex:int = currentElementIndex+1;
		playRequestedVideoIndexIfExists(requestedIndex);
	}
}

public function prevVideo():void{
	if(ShuffleState==true){
		var length:int=(gridData.length-1);
		playRequestedVideoIndexIfExists(generateRandomNumber(length));
	}else{	
		var requestedIndex:int = currentElementIndex-1;
		playRequestedVideoIndexIfExists(requestedIndex);
	}
}
public function hasNextVideo():Boolean{
	if((currentElementIndex==gridData.length-1)&&ShuffleState){
		return true;
	}else{
		return (currentElementIndex>=0 && currentElementIndex<gridData.length-1);
	}
}

public function startOver():void{
	playRequestedVideoIndexIfExists(0);
}

// retunrs number o-length
public function generateRandomNumber(end:int):int
{
	return Math.round( Math.random() * end);
}

public function setShuffle():Boolean
{	
	ShuffleState=!ShuffleState;
	return ShuffleState;
	
}

private function playRequestedVideoIndexIfExists(newIndex:int):void{
	if(newIndex>=0 && newIndex<gridData.length){
		var newVideo:Object = gridData.getItemAt(newIndex);
		songsDataGrid.selectedIndex = newIndex;
		currentElementIndex = newIndex;
		var playSongEvent:PlaySongEvent = new PlaySongEvent(newVideo,this,true);
		dispatchEvent(playSongEvent);
	}
}

//-------------------------------Search PlayList-----------------------------------------

private var searchString:String;


public function filter(text:String):void
{
	this.searchString = text;
	this.gridData.filterFunction = filterDataProvider;
	this.gridData.refresh();
}

public function filterDataProvider(obj:Object):Boolean {
	var itemName:String = (obj.name as String).toLowerCase();
	var itemArtist:String = (obj.artist as String).toLowerCase();
	var itemAlbum:String = (obj.album as String).toLowerCase();
	var itemGenre:String = (obj.genre as String).toLowerCase();
	
	return (itemName.indexOf(searchString) > -1) || (itemArtist.indexOf(searchString) > -1) ||
		(itemAlbum.indexOf(searchString) > -1) || (itemGenre.indexOf(searchString) > -1);
}

// ------------------------------ darg and drop rows --------------------------------------

/*import mx.controls.dataGridClasses.DataGridColumn;
import mx.events.DataGridEvent;

private var newIndex:int;
private var oldIndex:int;
private var draggedItem:Object;

private function onDragEnter(event:DragEvent):void {
	this.oldIndex = event.target.selectedIndex + 1;
	this.draggedItem = event.target.selectedItem;
}

private function onDragDrop(event:DragEvent):void{
}
	
private function onDragComplete(event:DragEvent):void{
	this.newIndex = this.gridData.getItemIndex(draggedItem) + 1;
	this.parentApplication.changeSongPos(this.getCurrentPlaylist(), draggedItem.keyString, oldIndex, newIndex);
}


private function doHeaderRelease(evt:DataGridEvent):void {
	var column:DataGridColumn = DataGridColumn(evt.currentTarget.columns[evt.columnIndex]);
	DataGrid(evt.currentTarget).callLater(onCallLater, [column]);
}

[Bindable]
private var canDrag:Boolean = true;

private function onCallLater(column:DataGridColumn):void {
	this.canDrag = (column.dataField == "rowNum") && !column.sortDescending;
	this.parentApplication.actionsListComp.debug.text = "canDrag: " + this.canDrag;
}
*/